package com.zxx.casserver.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zxx.cascommon.base.exception.ParamsException;
import com.zxx.cascommon.base.result.Result;
import com.zxx.cascommon.base.result.ResultUtils;
import com.zxx.casserver.modules.app.entity.AppDO;
import com.zxx.casserver.modules.app.entity.AppVO;
import com.zxx.casserver.modules.app.service.IAppService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 系统应用管理-前端控制器
 *
 * @author zhoukai
 * @since 2020-06-30
 */
@RestController
@RequestMapping("/app")
public class AppController {

    private final IAppService appService;

    public AppController(IAppService appService) {
        this.appService = appService;
    }


    @GetMapping("/test")
    public Result listAppTest(@RequestBody AppVO appVO) {
        QueryWrapper<AppDO> queryWrapper = new QueryWrapper<>();
        return ResultUtils.success(appService.list(queryWrapper));
    }

    @PostMapping("/list")
    public Result listApp(@RequestBody AppVO appVO) {
        IPage<AppDO> userPage = appService.listApp(appVO);
        if (ObjectUtils.isEmpty(userPage)) {
            return ResultUtils.fail(new JSONObject());
        }
        return ResultUtils.success(userPage);
    }

    @PostMapping("/save")
    public Result saveApp(@RequestBody AppVO appVO) {
        if (ObjectUtils.isEmpty(appVO.getName())) {
            throw new ParamsException();
        }
        if (ObjectUtils.isEmpty(appVO.getType())) {
            throw new ParamsException();
        }
        if (ObjectUtils.isEmpty(appVO.getUrl())) {
            throw new ParamsException();
        }
        if (ObjectUtils.isEmpty(appVO.getTestUrl())) {
            throw new ParamsException();
        }
        AppDO roleDO = appService.saveApp(appVO);
        if (ObjectUtils.isEmpty(roleDO)) {
            return ResultUtils.fail(new JSONObject());
        }
        return ResultUtils.success(roleDO);
    }

    @PostMapping("/update")
    public Result updateApp(@RequestBody AppVO appVO) {
        if (ObjectUtils.isEmpty(appVO.getAppId())) {
            throw new ParamsException();
        }
        AppDO roleDO = appService.updateApp(appVO);
        if (ObjectUtils.isEmpty(roleDO)) {
            return ResultUtils.fail(new JSONObject());
        }
        return ResultUtils.success(roleDO);
    }

    @PostMapping("/remove")
    public Result removeApp(@RequestBody AppVO appVO) {
        if (ObjectUtils.isEmpty(appVO.getAppId())) {
            throw new ParamsException();
        }
        AppDO roleDO = appService.removeApp(appVO);
        if (ObjectUtils.isEmpty(roleDO)) {
            return ResultUtils.fail(new JSONObject());
        }
        return ResultUtils.success(roleDO);
    }
}

